/**
 *
 */
package com.sinoglobal.dumping.base;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.dumplingspring.DumplingObservable;
import com.sinoglobal.dumping.util.Dumpling_AntiViolenceLisntener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author KeZhuang
 */
public abstract class Dumpling_SinoBaseActivity extends FragmentActivity implements Dumpling_AntiViolenceLisntener{
    private DumplingObservable mObservable = new DumplingObservable();
    protected FragmentManager mFragmentManager;

    private View mBaseActivityContainer;

    /**
     * 框架DIALOG
     */
    private Dumpling_DialogOfSetting mDialog;
    /**
     * 标题栏总布局
     */
    protected View mTemplateLayout;
    /**
     * 标题栏左边的图片
     */
    protected ImageView mTemplateLeftImg;
    /**
     * 标题栏右边的图片
     */
    protected ImageView mTemplateRightImg;
    /**
     * 标题栏左边的文字
     */
    protected TextView mTemplateLeftText;
    /**
     * 标题栏右边的文字
     */
    protected TextView mTemplateRightText;
    /**
     * 标题栏中间的文字
     */
    public TextView mTemplateTitleText;
    /**
     * 模版的主布局
     */
    protected FrameLayout mTemplateContainer;
    /**
     * 是否使用模版,true为使用,false则相反
     */
    protected boolean isTemplate = true;
    /**
     * Activity管理
     */
    private static List<Activity> sActivities = new ArrayList<Activity>();
    /**
     * 屏幕的宽度和高度
     */
    public int screenWidth;
    public int screenHeight;
    public int mTemplateHeight;
    /** 反暴力点击记录时间变量*/
    private long lastClickTime;

    public static List<Activity> getActivities() {
        return sActivities;
    }

    private Toast toast;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (!sActivities.contains(this)) {
            sActivities.add(this);
        }
        mDialog = new Dumpling_DialogOfSetting(this);
        mFragmentManager = getSupportFragmentManager();
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        setContentView(R.layout.dumpling_sinoglobal_template);
        initTemplate();
    }

    @Override
    public void onPanelClosed(int featureId, Menu menu) {
        super.onPanelClosed(featureId, menu);
    }

    /**
     * 退出App
     */
    public void exit() {
        for (Activity childActivity : sActivities) {
            if (childActivity != null) {
                childActivity.finish();
            }
        }
        Dumpling_SinoValueManager.clearValue(getApplicationContext(), false);
    }

    public DumplingObservable getObservable() {
        return mObservable;
    }

    private void initTemplate() {
        mTemplateContainer = (FrameLayout) findViewById(R.id.fl_view_mainBody);
        mTemplateContainer.setBackgroundColor(Color.WHITE);
        mTemplateLayout = findViewById(R.id.titleview);
        mTemplateLeftImg = (ImageView) findViewById(R.id.dumpling_title_left_btn_img);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 
	    int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 
	    mTemplateLayout.measure(w, h); 
	    mTemplateHeight = mTemplateLayout.getMeasuredHeight(); 
        if (!isTemplate) {
            mTemplateLayout.setVisibility(View.GONE);
        } else {
            mTemplateRightImg = (ImageView) findViewById(R.id.dumpling_title_right_btn_treaty);
            mTemplateRightImg.setOnClickListener(this);
            mTemplateLeftText = (TextView) findViewById(R.id.dumpling_title_left_tv);
            mTemplateRightText = (TextView) findViewById(R.id.dumpling_title_right_tv);
            mTemplateTitleText = (TextView) findViewById(R.id.dumpling_title_middle_tv);
            mTemplateLeftImg.setOnClickListener(this);
        }
    }

    /**
     * 显示一个toast
     *
     * @param message toast的内容
     */
    public void showToast(String message) {
        if (message == null) {
            return;
        }
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
        } else {
            toast.setText(message);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /** 子类调用super.onClick(v) 否则返回按钮无效*/
    @Override
    public void onClick(View v) {
        if(!isFastDoubleClick()){
            if(v.getId()==R.id.dumpling_title_left_btn_img){
                finish();
                overridePendingTransition(R.anim.dumpling_activity_on, R.anim.dumpling_activity_off);
            }else{
                onAntiViolence(v);
            }
        }
    }

    @Override
    public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if((time - lastClickTime) > 0 && (time - lastClickTime) < 1000){
            return true;
        }else{
            lastClickTime = time;
            return false;
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T getView(int resId){
        return (T)super.findViewById(resId);
    }


    /** 显示Dialog 提示框,无需调用dialog.dismiss方法
     * @param message dialog的提示消息
     * @param sureText dialog确定按键的text文本
     * @param cancelText dialog取消按键的text文本
     * @param listener dialog的监听
     */
    public void showDialog(Context context,String title, String message,String sureText, int sureColor, String cancelText,int cancelColor,boolean isShowCancel ,final DialogOnClickListener listener){
        if(message==null){
            throw new NullPointerException("提示框消息不能为空");
        }
        if(sureText==null||sureText.equals("")){
            sureText = "确定";
        }
        if(cancelText==null||cancelText.equals("")){
            cancelText = "取消";
        }
        final Dumpling_DialogOfSetting mDialog = new Dumpling_DialogOfSetting(context);
        mDialog.setmMessage(message);
        mDialog.setmTitle(title);
        mDialog.setShowBtn(isShowCancel);
        if(!isShowCancel){
            mDialog.mConfirm.setText(sureText);
            mDialog.mConfirm.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(listener!=null){
                        listener.onSure(view);
                    }
                    mDialog.dismiss();
                }
            });
        }
        mDialog.mCancle.setText(cancelText);
        mDialog.mCancle.setTextColor(getResources().getColor(cancelColor));
        mDialog.mSure.setText(sureText);
        mDialog.mSure.setTextColor(getResources().getColor(sureColor));
//        mDialog.mSure.setBackgroundResource(sureBackColor);
//        mDialog.mSure.setBackgroundColor(sureBackColor);
        mDialog.mCancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onCancle(v);
                }
                mDialog.dismiss();
            }
        });
        mDialog.mSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onSure(v);
                }
                mDialog.dismiss();
            }
        });
        mDialog.show();
    }

    /**
     * dialog的点击监听
     */
    public interface DialogOnClickListener{
        /** 确定回调
         */
        void onSure(View v);

        /**
         * 取消回调
         */
        void onCancle(View v);
    }
    /**
     * 显示一个Toast
     *
     * @param message 吐司的内容
     * @param time    吐司停留的时间
     */
    public void showToast(String message, int time) {
        if (message == null && time != -1) {
            return;
        }
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
        } else {
            toast.setText(message);
        }
        toast.show();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
    /**
     * 隐藏View方法,此方法隐藏会保留View的大小
     *
     * @param view 需要隐藏的View
     */
    public void hideView(View... view) {
        if (view.length > 0) {
            for (View viewParams : view) {
                viewParams.setVisibility(View.INVISIBLE);
            }
        }
    }

    /**
     * 隐藏View方法,此方法隐藏不保留View的大小
     *
     * @param view 需要隐藏的View
     */
    public void hideViewForGone(View... view) {
        if (view.length > 0) {
            for (View viewParams : view) {
                viewParams.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示View方法
     *
     * @param view 需要显示的View
     */
    public void showView(View... view) {
        if (view.length > 0) {
            for (View viewParams : view) {
                viewParams.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        if (layoutResID == R.layout.dumpling_sinoglobal_template) {
            mBaseActivityContainer = LayoutInflater.from(this).inflate(layoutResID, null);
            super.setContentView(mBaseActivityContainer);
        } else {
            mTemplateContainer.removeAllViews();
            View inflate = this.getLayoutInflater().inflate(layoutResID, null);
            inflate.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            mTemplateContainer.addView(inflate);
        }
    }

    @Override
    public void setContentView(View view) {
        setContentView(view, null);
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        if (mTemplateContainer != null) {
            mTemplateContainer.removeAllViews();
            if (params != null) {
                mTemplateContainer.addView(view, params);
            } else {
                mTemplateContainer.addView(view);
            }
        } else {
            super.setContentView(view, params);
        }
    }

    /**
     * intent封装 ,不支持参数,无参跳转
     *
     * @param toClsActivity 需要跳转到的activity
     */
    public void goIntent(Class<?> toClsActivity) {
        goIntent(toClsActivity, null);
    }

    /**
     * intent封装 ,支持参数携带
     *
     * @param toClsActivity 需要跳转到的activity
     * @param bundle        参数封装
     */
    public void goIntent(Class<?> toClsActivity, Bundle bundle) {
        Intent intent = new Intent(this, toClsActivity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * intent封装 ,隐式跳转
     *
     * @param action activity的action
     */
    public void goIntent(String action) {
        Intent intent = new Intent(action);
        startActivity(intent);
    }

    public Fragment getFragmentByTag(String tag){
        Fragment fragment = mFragmentManager.findFragmentByTag(tag);
        return fragment;
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.dumpling_push_left_in, R.anim.dumpling_push_left_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.dumpling_push_left_in, R.anim.dumpling_push_left_out);
    }

    /**
     * 是否登录
     * @return true 未登录  false 已经登录
     */
    public static boolean isNoLogIn(Context context){
        return Dumpling_SharedPreferenceUtil.isNoLogIn(context);
    }

    public static Map<String , OnLogInListener > observerMap=  new HashMap<String, OnLogInListener>();
    
    public interface OnLogInListener {
        void onLogInListener();
    }

    public synchronized void registerLogInListener(String id , OnLogInListener mLogInListener) {
        if(observerMap!=null){
            if (!observerMap.keySet().contains(id)){
                observerMap.put(id,mLogInListener);
            }
        }

    }

    public void unregisterLogInListener(String id){
        if(observerMap!=null){
            if (observerMap.keySet().contains(id)){
                observerMap.remove(id);
            }
        }
    }

    public void notifyLogInSuccess(){
        if(observerMap!=null){
            for (String key : observerMap.keySet()){
                observerMap.get(key).onLogInListener();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
